package controller

import (
	"GoGin/common"
	"GoGin/dto"
	"GoGin/model"
	"GoGin/response"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

func Register(r *gin.Context) {
	db := common.InitDB()

	name := r.PostForm("name")
	tel := r.PostForm("tel")
	pwd := r.PostForm("pwd")

	if len(tel) != 11 {
		response.Response(r, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位.")
		return
	}

	if len(pwd) < 6 {
		response.Response(r, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位.")
		return
	}

	if len(name) == 0 {
		response.Response(r, http.StatusUnprocessableEntity, 422, nil, "用户名不能为空.")
		return
	}

	if isExist(db, name) {
		response.Response(r, http.StatusUnprocessableEntity, 422, nil, "用户存在.")
		return
	}

	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(pwd), bcrypt.DefaultCost) // 加密密码
	if err != nil {
		response.Response(r, http.StatusUnprocessableEntity, 500, nil, "加密错误.")
		return
	}

	newUser := model.User{
		Name:      name,
		Telephone: tel,
		Password:  string(hasedPassword),
	}
	db.Create(&newUser)

	response.Success(r, nil, "注册成功!")
}

func Login(r *gin.Context) {
	db := common.InitDB()

	name := r.PostForm("name")
	pwd := r.PostForm("pwd")

	if len(pwd) < 6 {
		response.Response(r, http.StatusUnprocessableEntity, 422, nil, "密码不能少于6位.")
		return
	}

	if len(name) == 0 {
		response.Response(r, http.StatusUnprocessableEntity, 422, nil, "用户名不能为空.")
		return
	}

	var u1 model.User
	db.Where("name = ?", name).First(&u1)
	if u1.ID == 0 {
		response.Response(r, http.StatusUnprocessableEntity, 422, nil, "用户不存在.")
		return
	}

	err := bcrypt.CompareHashAndPassword([]byte(u1.Password), []byte(pwd)) // 解密密码
	if err != nil {
		response.Fail(r, nil, "密码错误.")
		return
	}

	// 发放token

	token, err := common.ReleaseToken(u1)
	if err != nil {
		response.Response(r, http.StatusUnprocessableEntity, 500, nil, "系统异常.")
		log.Printf("token generate error : %v", err)
		return
	}

	response.Success(r, gin.H{"token": token}, "登陆成功!")
	/* token：
	eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. 协议头 header 存储的加密协议
	eyJVc2VySUQiOjEsImV4cCI6MTY1NDA1MTU1NywiaWF0IjoxNjUzNDQ2NzU3LCJpc3MiOiJhZG1pbiIsInN1YiI6InVzZXIgdG9rZW4ifQ. 信息
	HSb_BKVGlmJ-yt_R-rld4YM6ToSZa-59KgvX45cToyA 哈希值
	*/
}

func Info(c *gin.Context) {
	user, _ := c.Get("user")
	// 返回了信息，但是很多信息是不可以被用户知道的，需要隐藏信息。
	response.Success(c, gin.H{"user": dto.ToUserDto(user.(model.User))}, "")
}

func isExist(db *gorm.DB, name string) bool {
	var u1 model.User                     // 声明一个结构体
	db.Where("name = ?", name).First(&u1) // gorm 提供的查询方式
	
	return u1.ID != 0
}
